package com.easymin.weixin.controller.v4;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.CommonUtil;
import com.easymin.weixin.common.PhoneNumberHelper;
import com.easymin.weixin.common.api.*;
import com.easymin.weixin.common.transport.Error;
import com.easymin.weixin.common.transport.Result;
import com.easymin.weixin.common.transport.ResultVo;
import com.easymin.weixin.entity.Order;
import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.entity.passenger.Passenger;
import com.easymin.weixin.entity.sales.Coupon;
import com.easymin.weixin.manager.ErrandManager;
import com.easymin.weixin.manager.FreightManager;
import com.easymin.weixin.manager.WxApplicationManager;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController("errandResV4")
@RequestMapping("api/errand/v4")
@SuppressWarnings("all")
public class ErrandRes {
  @Autowired
  private ErrandManager errandManager;
  @Autowired
  private WxApplicationManager wxApplicationManager;
  @Autowired
  private FreightManager freightManager;
  @Autowired
  private DaijiaApi daijiaApi;
  @Autowired
  private ZhuanApi zhuanApi;
  @Autowired
  private ZhuanXianApi zhuanXianApi;
  @Autowired
  private SalesApi salesApi;
  @Autowired
  private PassengerApi passengerApi;

  /**
   * V4根据电话号码查询客户姓名.
   */
  @RequestMapping(value = {"queryPassengerName"}, method = RequestMethod.GET)
  public ResultTransport queryPassengerName(@RequestParam("passengerPhone") String passengerPhone,
                                            @RequestParam("appKey") String appKey) {
    ResultTransport transport = passengerApi.findOneV4(passengerPhone, appKey);
    if (transport.getCode() == 0) {
      Map<String, Object> map = (Map<String, Object>) transport.getData();
      String passengerName = map.get("passengerName").toString();
      transport.setData(passengerName);
    }
    return transport;
  }

  /**
   * V4补单预算费用.
   */
  @RequestMapping(value = {"getPrice"}, method = RequestMethod.GET)
  public ResultTransport getPrice(@RequestParam("areaId") Long areaId, @RequestParam("time") Integer time,
                                  @RequestParam("mileage") Double mileage, @RequestParam(required = false, value = "weight") Double weight,
                                  @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    Double money = 0.0;
    ResultTransport transport = daijiaApi.getPriceByTimeAndMileageV4(wxApplication.getAddress(), areaId, time,
            mileage, weight);
    if (transport.getCode() == 0 && transport.getData() != null) {
      money = Double.valueOf(transport.getData().toString());
      transport.setData(money);
      return transport;
    } else {
      return transport;
    }
  }

  /**
   * V4确认费用重量预算费用.
   */
  @RequestMapping(value = {"getErrandWeightPrice"}, method = RequestMethod.GET)
  public ResultTransport getErrandWeightPrice(@RequestParam("orderId") Long orderId,
                                              @RequestParam("weight") Double weight, @RequestParam("mileage") Double mileage,
                                              @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    Double money = 0.0;
    ResultTransport transport = daijiaApi.getErrandWeightPriceV4(wxApplication.getAddress(), orderId, weight,
            mileage);//getErrandWeightPriceV4
    if (transport.getCode() == 0 && transport.getData() != null) {
      return transport;
    } else {
      return transport;
    }
  }

  /**
   * V4补单.
   */
  @RequestMapping(value = {"createmore"}, method = RequestMethod.POST)
  public ResultTransport createmore(@RequestParam("passengerPhone") String passengerPhone,
                                    @RequestParam(required = false, value = "passengerName") String passengerName,
                                    @RequestParam("employToken") String employToken, @RequestParam("startAddress") String startAddress,
                                    @RequestParam("startLat") Double startLat, @RequestParam("startLng") Double startLng,
                                    @RequestParam("content") String content, @RequestParam("orderTypeId") Long orderTypeId,
                                    @RequestParam(required = false, value = "deliverAddress") String deliverAddress,
                                    @RequestParam(required = false, value = "deliverLat") Double deliverLat,
                                    @RequestParam(required = false, value = "deliverLng") Double deliverLng,
                                    @RequestParam(required = false, value = "weight") Double weight,
                                    // @RequestParam(required = false, value = "shouldPay") Double shouldPay,
                                    // @RequestParam(required = false, value = "mileage") Double mileage,
                                    // @RequestParam(required = false, value = "travelTime") Integer travelTime,
                                    // @RequestParam(required = false, value = "startPrice") Double startPrice,
                                    // @RequestParam(required = false, value = "mileagePrice") Double mileagePrice,
                                    // @RequestParam(required = false, value = "travelTimePrice") Double
                                    // travelTimePrice,
                                    @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport transport = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);

    if (transport.getCode() == 0) {
      Map<String, Object> emap = (Map<String, Object>) transport.getData();

      Long employId = Long.valueOf(emap.get("employId").toString());
      Long employCompanyId = Long.valueOf(emap.get("companyId").toString());
      Double employScore = Double.valueOf(emap.get("employScore").toString());
      String employName = (String) emap.get("employName");
      String employPhone = (String) emap.get("employPhone");
      String employAccount = (String) emap.get("employAccount");
      String employPhoto = (String) emap.get("employPhoto");
      Double employLat = Double.valueOf(emap.get("employLat").toString());
      Double employLng = Double.valueOf(emap.get("employLng").toString());

      String employCompanyName = (String) emap.get("companyAbbreviation");

      int employJobStatus = (int) emap.get("employJobStatus");
      int employStatus = (int) emap.get("employStatus");
      String employJobType = (String) emap.get("employJobType");
      Long passengerId = null;
      passengerPhone = passengerPhone.replaceAll("-", "").replaceAll(" ", "");
      if (employJobType.contains("paotui") && (employJobStatus == 2 || employJobStatus == -1)
              && employStatus != 0) { // 包含跑腿业务,工作状态为跑腿或无任务,服务状态不为未上班
        transport = passengerApi.findOneV4(passengerPhone, appKey);
        if (transport.getCode() == 0) { // 老客户
          Map<String, Object> map = (Map<String, Object>) transport.getData();
          passengerId = Long.valueOf(map.get("passengerId").toString());
          passengerName = map.get("passengerName").toString();
        } else {
          transport = passengerApi.createPassengerV4(passengerPhone, passengerName, employCompanyId,
                  employCompanyName, "司机补单", appKey);
          if (transport.getCode() == 0 && transport.getData() != null) {
            Map<String, Object> map = (Map<String, Object>) transport.getData();
            passengerId = Long.valueOf(map.get("passengerId").toString());
            passengerName = map.get("passengerName").toString();
            passengerPhone = map.get("passengerPhone").toString();
            if (passengerId != null) {
              daijiaApi.newPassengerActivityV4(wxApplication.getAddress(), passengerId);
            }
          } else {
            return transport;
          }
        }

        List<Coupon> coupons = null;
        ResultTransport resultTransport = salesApi.findByPassengerIdV4(passengerId, "paotui", appKey);
        if (resultTransport.getCode() == 0 && resultTransport.getData() != null) {
          coupons = JSON.parseArray(resultTransport.getData().toString(), Coupon.class);
        }
        Long couponId = null;
        if (!CollectionUtils.isEmpty(coupons)) {
          couponId = coupons.get(0).getId();// 自动取第一张优惠券使用
        }
        ResultTransport resultTransport2 = errandManager.findOrderTypeV4(orderTypeId, appKey);
        if (resultTransport2.getCode() == 0 && resultTransport2.getData() != null) {
          Map<String, Object> map = (Map<String, Object>) resultTransport2.getData();
          Long areaId = Long.valueOf(map.get("areaId").toString());
          Double shouldPay = 0.0;
          Double mileage = 0.0;
          Integer travelTime = 0;
          Double startPrice = 0.0;
          Double mileagePrice = 0.0;
          Double travelTimePrice = 0.0;
          if (null == weight) {
            weight = 0D;
          }
          ResultTransport transport2 = daijiaApi.getPriceByAreaIdV4(wxApplication.getAddress(), areaId,
                  startLat, startLng, deliverLat, deliverLng);//, weight
          if (transport2.getCode() == 0 && transport2.getData() != null) {
            Map<String, Object> pmap = (Map<String, Object>) transport2.getData();
            shouldPay = Double.valueOf(pmap.get("money").toString());
            mileage = Double.valueOf(pmap.get("mileage").toString());
            travelTime = Integer.valueOf(pmap.get("time").toString());
            startPrice = Double.valueOf(pmap.get("startPrice").toString());
            mileagePrice = Double.valueOf(pmap.get("mileagePrice").toString());
            travelTimePrice = Double.valueOf(pmap.get("travelTimePrice").toString());

          }

          transport = errandManager.saveOrderV4(passengerId, passengerName, passengerPhone, employCompanyId,
                  employCompanyName, startAddress, startLat, startLng, deliverAddress, deliverLat, deliverLng,
                  "司机补单", startPrice, mileagePrice, travelTimePrice, mileage, travelTime, shouldPay,
                  orderTypeId, couponId, content, null, null, employId, employCompanyId, employName,
                  employPhone, appKey, weight);

          if (transport.getCode() == 0) {
            Long orderId = Long.valueOf(transport.getData().toString());
            daijiaApi.pushAcceptOrderV4(wxApplication.getAddress(), orderId, employId);
          }
          return transport;
        } else {
          return resultTransport2;
        }
      } else {
        if (employStatus != 1) {
          if (employStatus == 0) {
            transport.setMessage("您还没有上班，不能补单");
          } else {
            transport.setMessage("有未完成的工单，暂不能补单");
          }
        }
        transport.setCode(-21);
        return transport;
      }
    } else {
      return transport;
    }
  }

  /**
   * V4查询单个跑腿订单.
   */
  @RequestMapping(value = {"findOne"}, method = RequestMethod.GET)
  public ResultTransport findOne(@RequestParam("orderId") Long orderId, @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport resultTransport = errandManager.findOrderV4(orderId, appKey, wxApplication.getAddress());

    return resultTransport;
  }

  /**
   * V4查询跑腿类型.
   */
  @RequestMapping(value = {"queryType"}, method = RequestMethod.GET)
  public ResultTransport queryType(@RequestParam("companyId") Long companyId,
                                   @RequestParam(required = false, value = "employToken") String employToken,
                                   @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    String detailedJobType = "";
    if (StringUtils.isNotBlank(employToken)) {

      ResultTransport employResult = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
      if (employResult.getCode() != 0) {
        return employResult;
      }

      Map<String, Object> emap = (Map<String, Object>) employResult.getData();

      // 八达跑腿新增字段
      if (null != emap.get("detailedJobType")) {
        detailedJobType = emap.get("detailedJobType").toString();
      }
    }

    ResultTransport resultTransport = errandManager.queryTypeV4(companyId, detailedJobType, appKey);
    return resultTransport;
  }

  /**
   * 查询指定服务人员跑腿类型
   */
  @RequestMapping(value = {"queryByEmployeeToken"}, method = RequestMethod.GET)
  public ResultTransport queryByEmployeeToken(@RequestParam("companyId") Long companyId,
                                              @RequestParam(required = false, value = "employToken") String employToken,
                                              @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    String detailedJobType = "";
    if (StringUtils.isNotBlank(employToken)) {

      ResultTransport employResult = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
      if (employResult.getCode() != 0) {
        return employResult;
      }

      Map<String, Object> emap = (Map<String, Object>) employResult.getData();

      // 八达跑腿新增字段
      if (null != emap.get("detailedJobType")) {
        detailedJobType = emap.get("detailedJobType").toString();
      }
    }

    ResultTransport resultTransport = errandManager.queryTypeV4(companyId, detailedJobType, appKey);
    return resultTransport;
  }

  /**
   * V4接单.
   */
  @RequestMapping(value = {"jiedan"}, method = RequestMethod.POST)
  public ResultTransport jiedan(@RequestParam("orderId") Long orderId,
                                @RequestParam("employToken") String employToken, @RequestParam("appKey") String appKey, Boolean orderPool) {

    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    Long employId = Long.valueOf(emap.get("employId").toString());
    Long companyId = Long.valueOf(emap.get("companyId").toString());
    Double employScore = Double.valueOf(emap.get("employScore").toString());

    // 八达跑腿新增字段
    String errandserviceType = "";
    String platNo = "";
    if (null != emap.get("errandserviceType")) {
      errandserviceType = emap.get("errandserviceType").toString();
    }
    if (null != emap.get("platNo")) {
      platNo = emap.get("platNo").toString();
    }
    System.out.println("orderPool:" + orderPool);
    if (orderPool != null && orderPool) {
      String resultStr = errandManager.updateStatus(orderId, employId, (String) emap.get("employName"),
              (String) emap.get("employPhone"), companyId, "paidan", (String) emap.get("employName"), "", appKey);
      System.out.println("resultStr:" + resultStr);
    }
    ResultTransport instanceResult = errandManager.jiedan(orderId, employId, (String) emap.get("employName"),
            (String) emap.get("employPhone"), companyId, (String) emap.get("employAccount"),
            (String) emap.get("employPhoto"), employScore, (String) emap.get("employName"), appKey,
            errandserviceType, platNo);

    if (instanceResult.getCode() == 0) {
      instanceResult = daijiaApi.pushAcceptOrderV4(wxApplication.getAddress(), orderId, employId);
    }
    return instanceResult;
  }

  /**
   * V4抢单.
   */
  @RequestMapping(value = {"grab"}, method = RequestMethod.POST)
  public ResultTransport grab(@RequestParam("orderId") Long orderId, @RequestParam("employToken") String employToken,
                              @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }

    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    Long employId = Long.valueOf(emap.get("employId").toString());
    Long companyId = Long.valueOf(emap.get("companyId").toString());
    Double employScore = Double.valueOf(emap.get("employScore").toString());
    String employName = (String) emap.get("employName");
    String employPhone = (String) emap.get("employPhone");
    String employAccount = (String) emap.get("employAccount");
    String employPhoto = (String) emap.get("employPhoto");
    Double employLat = Double.valueOf(emap.get("employLat").toString());
    Double employLng = Double.valueOf(emap.get("employLng").toString());

    // 八达跑腿新增字段
    String errandserviceType = "";
    String platNo = "";
    if (null != emap.get("errandserviceType")) {
      errandserviceType = emap.get("errandserviceType").toString();
    }
    if (null != emap.get("platNo")) {
      platNo = emap.get("platNo").toString();
    }

    int employJobStatus = (int) emap.get("employJobStatus");
    int employStatus = (int) emap.get("employStatus");
    String employJobType = (String) emap.get("employJobType");
    ResultTransport instanceResult = new ResultTransport();
    if (employJobType.contains("paotui") && (employJobStatus == 2 || employJobStatus == -1) && employStatus != 0) { // 包含跑腿业务,工作状态为跑腿或无任务,服务状态不为未上班
      instanceResult = errandManager.toGrabOrderV4(orderId, employId, employName, employPhone, companyId,
              employLat, employLng, appKey, errandserviceType, platNo);

      if (instanceResult.getCode() == 0) {
        instanceResult = errandManager.grabOrderV4(orderId, employId, wxApplication.getAddress(), appKey);
        if (instanceResult.getCode() == 0) {
          instanceResult = daijiaApi.pushAcceptOrderV4(wxApplication.getAddress(), orderId, employId);
        }
      }
    } else {
      instanceResult.setCode(-21);
      instanceResult.setMessage("服务人员状态错误");
    }
    return instanceResult;
  }

  /**
   * V4拒单.
   */
  @RequestMapping(value = {"refuse"}, method = RequestMethod.POST)
  public ResultTransport refuse(@RequestParam("orderId") Long orderId,
                                @RequestParam("employToken") String employToken, @RequestParam("cause") String cause,
                                @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    Long employId = Long.valueOf(emap.get("employId").toString());

    String employName = (String) emap.get("employName");

    ResultTransport transport = errandManager.refuse(orderId, employId, cause, employName, appKey);
    if (transport.getCode() == 0) {
      transport = daijiaApi.pushRefuseErrandV4(wxApplication.getAddress(), orderId, employId, cause);
    }
    return transport;
  }

  /**
   * V4执行.
   */
  @RequestMapping(value = {"run"}, method = RequestMethod.POST)
  public ResultTransport runOrder(@RequestParam("orderId") Long orderId,
                                  @RequestParam("employToken") String employToken, @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport employResult = daijiaApi.findDriverV4Token(wxApplication.getAddress(), employToken);
    if (employResult.getCode() != 0) {
      return employResult;
    }
    Map<String, Object> emap = (Map<String, Object>) employResult.getData();

    String operator = (String) emap.get("employName");

    ResultTransport transport = errandManager.runV4(orderId, operator, appKey);

    if (transport.getCode() == 0) {
      transport = daijiaApi.pushRunOrderV4(wxApplication.getAddress(), orderId);
    }

    return transport;
  }

  /**
   * V4销单.
   */
  @RequestMapping(value = {"cancel"}, method = RequestMethod.POST)
  public ResultTransport cancel(@RequestParam("orderId") Long orderId, @RequestParam("cause") String cause,
                                @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport transport = errandManager.cancelV4(orderId, cause, appKey);

    if (transport.getCode() == 0) {
      transport = daijiaApi.pushDriverV4(wxApplication.getAddress(), orderId);
    }

    return transport;
  }

  /**
   * V4修改跑腿订单目的地.
   */
  @RequestMapping(value = {"updateToPlace"}, method = RequestMethod.POST)
  public ResultTransport updateToPlace(@RequestParam("orderId") Long orderId, @RequestParam("toPlace") String toPlace,
                                       @RequestParam("longitude") Double longitude, @RequestParam("latitude") Double latitude,
                                       @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport resultTransport = new ResultTransport();
    resultTransport = errandManager.updateToPlace(orderId, toPlace, longitude, latitude, appKey);
    return resultTransport;
  }

  /**
   * V4跑腿订单结算页面的数据.
   */
  @RequestMapping(value = {"completeTaskData"}, method = RequestMethod.GET)
  public ResultTransport completeTask(@RequestParam("orderId") Long orderId, @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport = daijiaApi.completeTaskErrandV4(wxApplication.getAddress(), orderId);

    return resultTransport;
  }

  /**
   * V4确认跑腿订单费用的接口.
   */
  @RequestMapping(value = {"confirmTask"}, method = RequestMethod.POST)
  public ResultTransport confirmTask(@RequestParam("orderId") Long orderId, @RequestParam("realCash") Double realCash,
                                     @RequestParam(required = false, value = "goodsCash") Double goodsCash,
                                     @RequestParam(required = false, value = "thanksCash") Double thanksCash,
                                     @RequestParam("guoluMoney") Double guoluMoney, @RequestParam("yuanchengMoney") Double yuanchengMoney,
                                     @RequestParam("otherMoney") Double otherMoney, @RequestParam("mileage") Double mileage,
                                     @RequestParam("waitedTime") Integer waitedTime, @RequestParam("travelTime") Integer travelTime,
                                     @RequestParam("startPrice") Double startPrice, @RequestParam("mileagePrice") Double mileagePrice,
                                     @RequestParam("runTimePrice") Double runTimePrice, @RequestParam("waitPrice") Double waitPrice,
                                     @RequestParam(required = false, value = "memo") String memo,
                                     @RequestParam(required = false, value = "jsonLocs") String jsonLocs,
                                     @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport = daijiaApi.confirmTaskErrandV4(wxApplication.getAddress(), orderId, realCash,
            goodsCash, thanksCash, guoluMoney, yuanchengMoney, otherMoney, mileage, waitedTime, travelTime,
            startPrice, mileagePrice, runTimePrice, waitPrice, memo, jsonLocs);

    return resultTransport;
  }

  /**
   * V4实时获取订单是否被结算.
   */
  @RequestMapping(value = {"checkTask"}, method = RequestMethod.GET)
  public ResultTransport checkTask(@RequestParam("orderId") Long orderId, @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);

    ResultTransport resultTransport = daijiaApi.checkTaskErrandV4(wxApplication.getAddress(), orderId);

    return resultTransport;
  }

  /**
   * V4最后结算接口.
   *
   * @param payType 支付类型: helppay(代付) sign(签单) balance(余额)
   * @param who     谁结算的
   */
  @RequestMapping(value = {"finishTask"}, method = RequestMethod.POST)
  public ResultTransport finishTask(@RequestParam("orderId") Long orderId, @RequestParam("payType") String payType,
                                    @RequestParam(required = false, value = "who") String who, @RequestParam("appKey") String appKey) {
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    ResultTransport resultTransport = daijiaApi.finishTaskErrandV4(wxApplication.getAddress(), orderId, payType,
            who);
    return resultTransport;
  }

  /**
   * 跑腿升级创建订单.
   *
   * @param passengerId     客户Id
   * @param passengerName   客户姓名
   * @param passengerPhone  客户电话
   * @param companyId       公司Id
   * @param companyName     公司名字
   * @param channelName     订单来源
   * @param startAddress    起点地址
   * @param startLat        起点地址纬度
   * @param startLng        起点地址经度
   * @param deliverAddress  交付地址
   * @param deliverLat      交付地纬度
   * @param deliverLng      交付地经度
   * @param startTime       预约时间
   * @param startPrice      起步价
   * @param mileagePrice    里程费
   * @param travelTimePrice 时间费
   * @param mileage         预计里程
   * @param travelTime      预计时间
   * @param shouldPay       预估价格
   * @param couponId        优惠券id
   * @param photo1          附件图片1
   * @param photo2          附件图片2
   * @param photo3          附件图片3
   * @param photo4          附件图片4
   * @param photo5          附件图片5
   * @param orderTypeId     跑腿类型id
   * @param content         任务文本
   * @param appKey          区分系统
   * @param recipients      收件人
   * @param phone           收件人电话
   * @param weight          重量
   * @param buyNeeds        购买需求
   * @param goodsCash       商品金额
   * @param thanksCash      感谢费
   * @param addServices     附加服务
   * @param tips            热门标签
   * @param startDetailed   详细开始地点
   * @param endDetailed     详细结束地点
   * @return 跑腿订单
   */
  @ResponseBody
  @RequestMapping(value = {"createByPassenger"}, method = RequestMethod.POST)
  public ResponseEntity<Object> createByPassenger(@RequestParam("passengerId") Long passengerId,
                                                  @RequestParam("passengerName") String passengerName, @RequestParam("passengerPhone") String passengerPhone,
                                                  @RequestParam("companyId") Long companyId, @RequestParam("companyName") String companyName,
                                                  @RequestParam("channelName") String channelName,
                                                  @RequestParam(required = false, value = "startAddress") String startAddress,
                                                  @RequestParam(required = false, value = "startLat") Double startLat,
                                                  @RequestParam(required = false, value = "startLng") Double startLng,
                                                  @RequestParam(required = false, value = "deliverAddress") String deliverAddress,
                                                  @RequestParam(required = false, value = "deliverLat") Double deliverLat,
                                                  @RequestParam(required = false, value = "deliverLng") Double deliverLng,
                                                  @RequestParam(required = false, value = "startTime") Long startTime,
                                                  @RequestParam(required = false, value = "startPrice") Double startPrice,
                                                  @RequestParam(required = false, value = "mileagePrice") Double mileagePrice,
                                                  @RequestParam(required = false, value = "travelTimePrice") Double travelTimePrice,
                                                  @RequestParam(required = false, value = "mileage") Double mileage,
                                                  @RequestParam(required = false, value = "travelTime") Integer travelTime,
                                                  @RequestParam(required = false, value = "shouldPay") Double shouldPay,
                                                  @RequestParam(required = false, value = "orderTypeId") Long orderTypeId,
                                                  @RequestParam(required = false, value = "couponId") Long couponId,
                                                  @RequestParam(required = false, value = "photo1") MultipartFile photo1,
                                                  @RequestParam(required = false, value = "photo2") MultipartFile photo2,
                                                  @RequestParam(required = false, value = "photo3") MultipartFile photo3,
                                                  @RequestParam(required = false, value = "photo4") MultipartFile photo4,
                                                  @RequestParam(required = false, value = "photo5") MultipartFile photo5,
                                                  @RequestParam(required = false, value = "content") String content,
                                                  @RequestParam(required = false, value = "startDetailed") String startDetailed,
                                                  @RequestParam(required = false, value = "endDetailed") String endDetailed,
                                                  @RequestParam(required = false, value = "recipients") String recipients,
                                                  @RequestParam(required = false, value = "phone") String phone,
                                                  @RequestParam(required = false, value = "weight") String weight,
                                                  @RequestParam(required = false, value = "matter") String matter,
                                                  @RequestParam(required = false, value = "buyNeeds") String buyNeeds,
                                                  @RequestParam(required = false, value = "goodsCash") Double goodsCash,
                                                  @RequestParam(required = false, value = "thanksCash") Double thanksCash,
                                                  @RequestParam(required = false, value = "addServices") String addServices,
                                                  @RequestParam(required = false, value = "tips") String tips,
                                                  @RequestParam(required = true, value = "prePay") boolean prePay,
                                                  @RequestParam(required = true, value = "payType") String payType, HttpServletRequest req,
                                                  @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;
    WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
    try {
      appKey = StringUtils.trimToEmpty(appKey);
      Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
      // 哒哒定制
      if (appKey.equals("a1f4d7d78a854565930fcee06e2b4d1d")) {
        boolean istrue = daijiaApi.isCreateOrderNumberErrand(wxApplication.getAddress(), appKey, passengerId);
        if (!istrue) {
          Error error = new Error(-1, "您今日下单已达到上限，继续下单请联系客服。");
          responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
          return responseEntity;
        }
      }

      if (!payType.equals(Order.PayTypeDetails.coupon.toString())
              && !payType.equals(Order.PayTypeDetails.sign.toString())
              && !payType.equals(Order.PayTypeDetails.balance.toString())) {
        Error error = new Error(-1, "支付方式应为优惠券、余额或签单支付");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }

      if (StringUtils.isNotBlank(content) && content.length() > 200) {
        Error error = new Error(-41, "内容长度过长");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (null == companyId || StringUtils.isBlank(companyName)) {
        Error error = new Error(-1, "参数错误:公司不能为空");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (passengerId == null || passengerId == 0) {
        Error error = new Error(-20, "参数错误:客户不存在");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }
      if (!PhoneNumberHelper.isPhoneNumber(passengerPhone)) {
        Error error = new Error(-1, "参数错误:电话号码格式不正确");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }

      Passenger passenger = passengerApi.findById(passengerId, appKey);
      // 并行单量判断
      Long count = errandManager.countNotFinishedByPassenger(passengerId, appKey);
      Long number = 1L;
      if (null != passenger.getPassengerGrade() && passenger.getPassengerGrade().getParallelOrderNumber() > 0
              && count + number > passenger.getPassengerGrade().getParallelOrderNumber()) {
        Error error = new Error(-86, "您当前有" + count + "个订单未结束!不能再下新单。");
        responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
        return responseEntity;
      }

      JSONObject object = daijiaApi.getServices(wxApplication.getAddress());
      if (object != null) {
        Long num = 0L;
        boolean daijia = object.getBooleanValue("daijia");
        if (daijia) {
          num += daijiaApi.countNotPayAmounts(wxApplication.getAddress(), passengerId);
        }
        boolean zhuanche = object.getBooleanValue("zhuanche");
        if (zhuanche) {
          num += zhuanApi.countNotPayAmounts(passengerId, appKey);
        }
        boolean paotui = object.getBooleanValue("paotui");
        if (paotui) {
          num += errandManager.countNotPayAmounts(passengerId, appKey);
        }
        boolean freight = object.getBooleanValue("freight");
        if (freight) {
          num += freightManager.countNotPayAmounts(passengerId, appKey);
        }
        boolean zhuanxian = object.getBooleanValue("zhuanxian");
        if (zhuanxian) {
          num += zhuanXianApi.countNotPayAmounts(passengerId, appKey);
        }
        if (num > 0) {
          Error error = new Error(-54, "还有未完成支付的订单，不能下单");
          responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
          return responseEntity;
        }
      }

      // Long countRunning = errandManager.countRunning(passengerId, appKey);
      // if (countRunning > 10) {
      // Error error = new Error(-55, "您今日下单已达到上限，继续下单请联系客服");
      // responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
      // return responseEntity;
      // }

      String address = wxApplication.getAddress();// 代驾地址

      // 判断余额是否够等。。
      if (prePay) {
        ResultVo balancesignPayCheck = daijiaApi.balancesignPayCheck(address, shouldPay, passengerId, payType,
                couponId);
        if (!balancesignPayCheck.isSuccess()) {
          Error error = new Error(-1, balancesignPayCheck.getMessage());
          responseEntity = new ResponseEntity<Object>(error, HttpStatus.OK);
          return responseEntity;
        }
      }

      Date startDate = null;
      if (null != startTime) {
        startDate = new Date(startTime);// 开始时间
      }

      Order order = errandManager.saveOrder(passengerId, passengerName, passengerPhone, companyId, companyName,
              startAddress, startLat, startLng, deliverAddress, deliverLat, deliverLng, channelName, startDate,
              startPrice, mileagePrice, travelTimePrice, mileage, travelTime, shouldPay, orderTypeId, couponId,
              content, null, null, null, null, null, null, appKey, startDetailed, endDetailed, recipients, phone,
              weight, buyNeeds, goodsCash, thanksCash, addServices, tips, matter, prePay, payType, address);

      String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
              + req.getContextPath();

      String imgs = "";
      if (photo1 != null) {
        String photo1Url = CommonUtil.uploadErrandImg(photo1, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo1Url);
        imgs = img;
      }
      if (photo2 != null) {
        String photo2Url = CommonUtil.uploadErrandImg(photo2, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo2Url);
        imgs += "," + img;
      }
      if (photo3 != null) {
        String photo3Url = CommonUtil.uploadErrandImg(photo3, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo3Url);
        imgs += "," + img;
      }
      if (photo4 != null) {
        String photo4Url = CommonUtil.uploadErrandImg(photo4, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo4Url);
        imgs += "," + img;
      }
      if (photo5 != null) {
        String photo5Url = CommonUtil.uploadErrandImg(photo5, req);
        String img = daijiaApi.uploadImg(address, order.getId(), basePath + "/" + photo5Url);
        imgs += "," + img;
      }
      if (StringUtils.isNotBlank(imgs)) {
        errandManager.saveOrderImgs(order.getId(), channelName, imgs, appKey);
      }
      if (null != order.getId()) {
        daijiaApi.pushNewOrder(address, order.getId());
      }

      Result<Map<String, Object>> result = new Result<Map<String, Object>>(0, "成功", null);
      responseEntity = new ResponseEntity<Object>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(-4, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }
  }

}
